# -*- coding: utf-8 -*-
# Created by methew at 2018/6/2
import random
import string
import time
from itsdangerous import URLSafeTimedSerializer, BadSignature, BadTimeSignature
from hashlib import md5


class Serializer:
    _code = ''
    _RawData = []
    _app = None

    def __init__(self, app):
        self._app = app
        self.sl = URLSafeTimedSerializer(
            app.config['SECRET_KEY'], app.config['SECURITY_TOKEN_SALT'])

    def serialize_data(self, data):
        time_data = str(int(time.time())).encode('utf-8')
        time_hash_data = '.' + md5(time_data).hexdigest()
        self._code = ''.join(random.sample(
            string.ascii_letters + string.digits, 10)) + time_hash_data
        self._RawData.append(self._code)
        return self.sl.dumps(self._RawData.append(data))

    def deserialize_data(self, decode_data):
        try:
            return self.sl.loads(decode_data, self._app.config['SECURITY_TOKEN_MAX_AGE'])
        except (BadSignature, BadTimeSignature):
            return None

    def get_code(self):
        return self._code
